<?php

namespace app\store\controller;
use think\Request;
use think\Validate;
use think\Db;
use think\Cache;
class Goods extends ApiCommon
{	
	public function homeindex(){
		//首页
		$request = Request::instance();
		$data = $request->param();
		if (!$request->isPost()) {
			return $this->ErrorSend('ispost');
		}
		
		$rule = [
		    'storeid'  => 'require|number'
		];		
		$msg = [
		    'storeid.require' => 'storeid null',
		    'storeid.number' => 'storeid is number'
		];
		
		$validate = new Validate($rule, $msg);
		$result   = $validate->check($data);
		
		if(!$result){
			return json_encode(['error'=>$validate->getError()]);
		}
		
		$storeid = $data['storeid'];
		
		
		//查询顶部商品
		$topResult = Db::query("select id,gname,message,price,type,icon,showType,buyType,buynum,topicon,discount from ml_goods where isshow = 1 and showType=1 and storeid =?",[$storeid]);	
		
		//其他首页商品
		$result = Db::query("select id,gname,message,price,type,icon,showType,buyType,buynum,topicon,discount from ml_goods where isshow = 1 and showType>1 and showType<4 and type<10 and storeid =?",[$storeid]);	
		
		$showArr = array();	
		foreach ($result as $key => $value) {
			$Types = $value['showType'];
			if(!isset($showArr[$Types])){
				$showArr[$Types] = array();
			}			
			array_push($showArr[$Types],$value);
		}
		
		$backArr = [];
		$backArr['error']='ok';
		//顶部推荐
		$backArr['arrtop'] = $topResult;		
		//推荐
		$backArr['tuiarr'] = [];
		//热卖
		$backArr['hotarr'] = [];

		if(isset($showArr[2])){
			$backArr['tuiarr'] = $showArr[2];
		}
		
		if(isset($showArr[3])){
			$backArr['hotarr'] = $showArr[3];
		}
		
		$json_objback = json_encode($backArr);
		return $json_objback;
	}
	
	//获得商品详细信息
	function goodsmsg(){
		$request = Request::instance();
		
		if (!$request->isPost()) {
			return $this->ErrorSend('ispost');
		}
		
		$data = $request->param();		
		
		$rule = [
		    'goodsid'  => 'require|number'
		];		
		$msg = [
		    'goodsid.require' => 'goodsid null',
		    'goodsid.number' => 'goodsid is number'
		];
		
		$validate = new Validate($rule, $msg);
		$result   = $validate->check($data);
		
		if(!$result){
			return json_encode(['error'=>$validate->getError()]);
		}
		
		$goodsid = $data['goodsid'];
		$result = Db::query("SELECT * from ml_goodsimage where goodsid = ?",array($goodsid));	
		$htmlRes = Db::query("SELECT id,gname,message,price,icon,addtime,htmlmsg,type,buyType,discount,usetime from ml_goods where id = ?",array($goodsid));
		$attResult = Db::query("SELECT * from ml_goods_att where gid = ?",array($goodsid));			
		
		$backArr = ['imgarr'=>$result,'ginfo'=>$htmlRes[0],'att'=>$attResult];	
		$this->returnMsg('ok','',$backArr);
	}
	
	//资讯详情
	function informactionmsg(){
		$request = Request::instance();
		
		if (!$request->isPost()) {
			return $this->ErrorSend('ispost');
		}
		
		$data = $request->param();		
		
		$rule = [
		    'goodsid'  => 'require|number'
		];		
		$msg = [
		    'goodsid.require' => 'goodsid null',
		    'goodsid.number' => 'goodsid is number'
		];
		
		$validate = new Validate($rule, $msg);
		$result   = $validate->check($data);
		
		if(!$result){
			return json_encode(['error'=>$validate->getError()]);
		}
		
		$goodsid = $data['goodsid'];
		$htmlRes = Db::query("SELECT * from ml_information where id = ?",array($goodsid));
		
		$gameInfo = Db::name("info_game")->where(['infoid'=>$goodsid])->find();
		
		$backArr = ['imgarr'=>[],'ginfo'=>$htmlRes[0],'att'=>[],'gameinfo'=>$gameInfo];	
		$this->returnMsg('ok','',$backArr);
	}
	
	
	//获得商品列表
	function goods_list(){
		$types = input('type/d',0);
		$page = input('page/d',0);
		$storeid = input('storeid/d',1);
		$goodstp = input('goodstp/d',0);
		$tparr = get_goodstp($storeid);
		$arr = get_goods_bytp($types,$page,$storeid,$goodstp);		
		$this->returnMsg('ok','',['arr'=>$arr,'tparr'=>$tparr,'type'=>$types]);
	}
	
	//商品检查是否可以购买
	
	//获得购买记录
	public function getBuyList(){
		
		$userid = input('uid');
		$page = input('page');
		
		$pagesize = config('PageSize');
		$startpage = $pagesize*$page;
		
		$selectSql = "select ml_buylist.*,icon,message,ml_goods.price as goodsprice,ml_goods.id,ml_goods.type FROM ml_buylist,
		ml_goods where ml_buylist.userid = ? and ml_buylist.goodsid = ml_goods.id and paystate >0 
		order by buydate desc limit ?,?";

		
		$result = Db::query($selectSql,[$userid,$startpage,$pagesize]);
		$this->returnMsg('ok','',$result);		
	}
	
	//获得商品下的优惠券状态
	public function getCoupon(){
			
		$buyid = input('buyid/d',0);

		$result = Db::query("select ml_coupon.*,ml_consumelist.* from ml_consumelist,ml_coupon where ml_consumelist.coupon = ml_coupon.id 
		and ml_consumelist.buyid =$buyid order by states asc");

		$this->returnMsg('ok','',$result);	
	}
	
	
	public function redistest(){
		Cache::store('redis')->set('name123','value/...p');
		$this->returnMsg('ok','',Cache::get('name'));	
	}
	
	//老板提现
	//短信验证
	//购买下订单操作
	//购买操作
	//1.用户消费
	//2.老板获得钱
	//3.老板提取
	
	//使用优惠券
	public function useCoupon(){		
		
		$uuid = input('cuid/d',0);
		$userid = input('userid/d',0);
		$BossUserid = input('uid/d',0);
		$buyid = input('buyid/d',0);
		
		
		$result = Db::query("select * from ml_consumelist where consumeid = $uuid");
		if(count($result)<=0){
			$this->returnMsg('-1','优惠券不存在'.$uuid);	
		}
		
		if($result[0]['states'] == 1){
			$this->returnMsg('-1','优惠券已经被使用');	
		}
		
		$goodsid = $result[0]['goodsid'];
		$goodsRes = Db::query("select commissionboss,price,giveIntegral,type from ml_goods where id = ?",array($goodsid));
		if(count($goodsRes)<=0){
			$this->returnMsg('-1','商品不存在');	
		}
		
		$Boss = config('Boss');
		$User = config('User');
		$starttm = $result[0]['datefrom'];
		$endtm = $result[0]['dateto'];
		$curtime = time();
		if($curtime<$starttm || $curtime>$endtm){
			$this->returnMsg('-1','优惠券不在有限时间范围内');	
		}
		
		$roleresult = Db::query("select role,storeid from ml_userinfo where userid = ? ",array($BossUserid));
		if(count($roleresult)<=0){
			$this->returnMsg('-1','商户信息不存在');	
		}
		if($roleresult[0]['role'] != $Boss){
			$this->returnMsg('-1','商户信息错误');	
		}
		
		$storeid = $roleresult[0]['storeid'];
		
		$userroleresult = Db::query("SELECT role from ml_userinfo where userid = ? ",array($userid));
		if(count($userroleresult)<=0){
			$this->returnMsg('-1','用户信息不存在');	
		}
		if($userroleresult[0]['role'] != $User){
			$this->returnMsg('-1','用户信息错误');
		}
		
	
		$cpuuid = $result[0]['coupon'];
		
		$couponresult = Db::query("select * from ml_coupon where id = ?",array($cpuuid));	
		if(count($couponresult)<=0){
			$this->returnMsg('-1','优惠券不存在');
		}
		
		$buyresult = Db::query("select * from ml_buylist where buyid = ?",array($buyid));
		//交易订单不存在
		if(count($buyresult)<=0){
			$this->returnMsg('-1','交易订单不存在');
		}
		
		$orderstate = config('orderstate');
		$paystate = config('paystate');
		
		//订单状态不对
		if($buyresult[0]['orderstate']>=$orderstate['UseEnd'] || $buyresult[0]['paystate']!=$paystate['Pay']){
			$this->returnMsg('-1','订单未支付');
		}
		
		//订单userid和交易订单userid不同
		$buyUserid = $buyresult[0]['userid'];
		if($buyUserid != $userid){
			$this->returnMsg('-1','订单错误');
		}
		
		//修改订单状态
		db('consumelist')->where(['consumeid'=>$uuid])->save(['states'=>1,'consumedate'=>time()]);
		
			
		//更改订单状态
		$couponlistResult = Db::query("select consumeid from ml_consumelist where buyid = $buyid and states = 0");
		if(count($couponlistResult)<=0){
			Db::query("update ml_buylist set orderstate = 2 where buyid = $buyid");
		}
			
		$client = Db::query("select * from ml_clientslist where belongto = ? and clientid = ?",array($BossUserid,$userid));
		if(count($client)<=0){
			//说明没有确定关系
			Db::query("insert into ml_clientslist(clientid,belongto,conndate,agentid)values(?,?,?,?)",array($userid,$BossUserid,time(),0));
		}		
		$userinoutResult = Db::query("select * from ml_goodsuse where bossid = ? and userid = ? and buyid = ?",array($BossUserid,$userid,$buyid));
		if(count($userinoutResult)<=0){		
			
			$lastid = db('goodsuse')->add(['bossid'=>$BossUserid,'userid'=>$userid,'goodsid'=>$goodsid,'usetime'=>time(),'buyid'=>$buyid,'storeid'=>$storeid]);

			//修改分成关系				
			$price = $buyresult[0]['price']*0.01;
			$bossMoney = floatval($goodsRes[0]['commissionboss'] * $price);
			$giveIntegral = $goodsRes[0]['giveIntegral'];
			
			//用户信息	
			Db::query("insert into ml_goodsusemsg(usetype,useid,userid,nums,opdate,userrole,goodsname,storeid)values(?,?,?,?,?,?,?,?)",
			array(4,$lastid,$userid,$giveIntegral,time(),$User,$couponresult[0]['cname'],$storeid));	
			
			//老板娘自己的
			Db::query("insert into ml_goodsusemsg(usetype,useid,userid,nums,opdate,userrole,goodsname,storeid)values(?,?,?,?,?,?,?,?)",
			array(4,$lastid,$BossUserid,$bossMoney,time(),$Boss,$couponresult[0]['cname'],$storeid));						
		}
		
		$resUseKey = 'use:userid:'.$userid.':'.$uuid;
		Cache::store('redis')->set($resUseKey,'userid='.$userid,80);
		$this->returnMsg('ok','使用成功',$resUseKey);		

	}
	
	//获得使用状态
	function couponstate_handle(){
		
		$hand = input('hand');
		
		$ishave = Cache::store('redis')->has($hand);
		
		if($ishave){
			Cache::store('redis')->rm($hand);		
			$this->returnMsg('ok','使用成功');				
		}
		else{
			$this->returnMsg('-1','fail',$hand);
		}
		
	}
}
?>